package cn.xyfmzmy.eventloop;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MzmyEventLoopGroup implements EventLoopGroup{

    private final EventLoop[] children;

    private final AtomicInteger index = new AtomicInteger(0);

    public MzmyEventLoopGroup(int threadNum) {
        this.children = new EventLoop[threadNum];
        for(int i=0;i<threadNum;i++){
            children[i] = new MzmyEventLoop();
        }
    }

    @Override
    public void execute(Runnable task) {
        if( task instanceof TargetRunnable targetRunnable){
            // 如果是TargetRunnable，就强转并指定EventLoop执行
            children[targetRunnable.getIndex()].execute(task);
        }else{
            next().execute(task);
        }
    }

    @Override
    public void schedule(Runnable task, long delay, TimeUnit unit) {
        if( task instanceof TargetRunnable targetRunnable){
            // 如果是TargetRunnable，就强转并指定EventLoop执行
            children[targetRunnable.getIndex()].schedule(task,delay,unit);
        }else{
            next().schedule(task, delay, unit);
        }

    }

    @Override
    public void scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit) {
        if( task instanceof TargetRunnable targetRunnable){
            // 如果是TargetRunnable，就强转并指定EventLoop执行
            children[targetRunnable.getIndex()].scheduleAtFixedRate(task,initialDelay,period,unit);
        }else{
            next().scheduleAtFixedRate(task, initialDelay, period, unit);
        }
    }

    @Override
    public EventLoop next() {
        return children[index.getAndIncrement() % children.length];
    }
}
